package com.zhentao.datacontrol.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.datacontrol.domain.entity.DataControlRule;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface DataControlRuleMapper extends BaseMapper<DataControlRule> {

    /**
     * 分页查询规则列表（带分组信息）
     */
    @Select("<script>" +
            "SELECT r.*, g.group_name " +
            "FROM dc_rule r " +
            "LEFT JOIN dc_rule_group g ON r.group_id = g.id " +
            "WHERE r.is_delete = 0 " +
            "<if test='groupId != null'> AND r.group_id = #{groupId} </if>" +
            "<if test='ruleName != null and ruleName != \"\"'> AND r.rule_name LIKE CONCAT('%', #{ruleName}, '%') </if>" +
            "<if test='status != null and status != \"\"'> AND r.status = #{status} </if>" +
            "<if test='publishStatus != null and publishStatus != \"\"'> AND r.publish_status = #{publishStatus} </if>" +
            "ORDER BY r.group_id, r.sort_order, r.id" +
            "</script>")
    IPage<DataControlRule> selectPageWithGroup(Page<DataControlRule> page,
                                             @Param("groupId") Long groupId,
                                             @Param("ruleName") String ruleName,
                                             @Param("status") String status,
                                             @Param("publishStatus") String publishStatus);

    /**
     * 查询分组下的所有规则
     */
    @Select("SELECT r.*, g.group_name " +
            "FROM dc_rule r " +
            "LEFT JOIN dc_rule_group g ON r.group_id = g.id " +
            "WHERE r.group_id = #{groupId} AND r.is_delete = 0 " +
            "ORDER BY r.sort_order, r.id")
    List<DataControlRule> selectByGroupId(@Param("groupId") Long groupId);

    /**
     * 检查规则编码是否存在
     */
    @Select("SELECT COUNT(*) FROM dc_rule " +
            "WHERE rule_code = #{ruleCode} AND is_delete = 0 " +
            "AND (#{id} IS NULL OR id != #{id})")
    int checkRuleCodeExists(@Param("ruleCode") String ruleCode, @Param("id") Long id);

    /**
     * 获取下一个规则编码
     */
    @Select("SELECT CONCAT('RULE_', LPAD(COALESCE(MAX(CAST(SUBSTRING(rule_code, 6) AS UNSIGNED)), 0) + 1, 6, '0')) " +
            "FROM dc_rule " +
            "WHERE rule_code LIKE 'RULE_%' AND is_delete = 0")
    String getNextRuleCode();

    /**
     * 更新规则状态
     */
    @Update("UPDATE dc_rule SET status = #{status}, updated_time = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") String status);

    /**
     * 更新发布状态
     */
    @Update("UPDATE dc_rule SET publish_status = #{publishStatus}, updated_time = NOW() WHERE id = #{id}")
    int updatePublishStatus(@Param("id") Long id, @Param("publishStatus") String publishStatus);

    /**
     * 移动规则到指定分组
     */
    @Update("UPDATE dc_rule SET group_id = #{groupId}, updated_time = NOW() WHERE id = #{id}")
    int moveToGroup(@Param("id") Long id, @Param("groupId") Long groupId);

    /**
     * 更新排序号
     */
    @Update("UPDATE dc_rule SET sort_order = #{sortOrder}, updated_time = NOW() WHERE id = #{id}")
    int updateSortOrder(@Param("id") Long id, @Param("sortOrder") Integer sortOrder);

    /**
     * 查询已发布的规则
     */
    @Select("SELECT r.*, g.group_name " +
            "FROM dc_rule r " +
            "LEFT JOIN dc_rule_group g ON r.group_id = g.id " +
            "WHERE r.publish_status = 'PUBLISHED' AND r.status = 'ENABLED' " +
            "AND r.is_delete = 0 " +
            "AND (r.effective_end_date IS NULL OR r.effective_end_date >= CURDATE()) " +
            "ORDER BY r.rule_priority, r.id")
    List<DataControlRule> selectPublishedRules();

    /**
     * 根据分组查询规则树形结构
     */
    @Select("SELECT r.*, g.group_name " +
            "FROM dc_rule r " +
            "LEFT JOIN dc_rule_group g ON r.group_id = g.id " +
            "WHERE r.is_delete = 0 " +
            "ORDER BY g.sort_order, r.sort_order, r.id")
    List<DataControlRule> selectRuleTree();
}
